package com.demo.utils;


import com.demo.security.AuthUserDetail;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;

import java.util.*;

public class JwtUtil {
    private static final String TOKEN_SECRET = "DD5654D654DSD5S1D65S4D65S1D";
    public static final String TOKEN_PREFIX = "DEMO_";
    public static final String HEADER_STRING = "X-Token";
    private static final long EXPIRATION = 24 * 3600L;

    public static String createJWT(AuthUserDetail auth) {
        //指定签名的时候使用的签名算法，也就是header中的 算法
        //生成JWT的时间

        Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
        StringBuffer as = new StringBuffer();
        for (GrantedAuthority authority : authorities) {
            as.append(authority.getAuthority())
                    .append(",");
        }
        //创建payload的私有声明(根据特定的业务需要添加，如果要拿这个做验证,一般是需要和JWT的接受方提前沟通)
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("authorities", as);
        claims.put("username", auth.getUsername());
        claims.put("userId", auth.getUserId());
        claims.put("roleId", auth.getRoleId());
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, TOKEN_SECRET)
                .setSubject(auth.getUsername())
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION * 1000))
                .compact();

    }

    public static AuthUserDetail parseJWT(String token) {

        token = token.substring(JwtUtil.TOKEN_PREFIX.length());
        Claims claims = Jwts.parser()
                .setSigningKey(TOKEN_SECRET)
                .parseClaimsJws(token)
                .getBody();
        String userId = claims.get("userId").toString();
        String username = claims.get("username").toString();//获取当前登录用户名
        String roleId = claims.get("roleId").toString();


        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities"));
        AuthUserDetail detail = new AuthUserDetail();
        detail.setRoleId(roleId);
        detail.setUsername(username);
        detail.setUserId(userId);

        return detail;

    }


}
